package com.ruoyi.hqfinance.controller;

import cn.hutool.core.net.URLEncoder;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.domain.vo.TablePointVo;
import com.ruoyi.common.service.TableService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.hqfinance.domain.HqNetworkBillDetail;
import com.ruoyi.hqfinance.domain.vo.HqNetworkBillDetailVo;
import com.ruoyi.hqfinance.domain.vo.HqNetworkBillPointVo;
import com.ruoyi.hqfinance.service.HqNetworkBillDetailService;
import com.ruoyi.logistic.domain.PageDate;
import com.ruoyi.logistic.domain.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/hq/billDetail")
@Api(tags = "总部财务-网点账单明细")
@EnableAsync
public class HqNetworkBillDetailController {
    @Autowired
    private HqNetworkBillDetailService hqNetworkBillDetailService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private TableService tableService;

    private final StringRedisTemplate stringRedisTemplate;
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    public HqNetworkBillDetailController(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @ApiOperation("查全部")
    @GetMapping("/selectAll")
    public R selectAll(PageDate pageDate) {
        List<HqNetworkBillDetail> billDetailList = hqNetworkBillDetailService.selectAll(pageDate);
        if (billDetailList == null || billDetailList.size() == 0) {
            return R.fail("暂无数据");
        } else {
            return R.ok(PageInfo.info(billDetailList));
        }
    }

    @ApiOperation("添加")
    @PostMapping("/insert")
    public R insert(@RequestBody HqNetworkBillDetail hqNetworkBillDetail) {
        Boolean isAdd = hqNetworkBillDetailService.insert(hqNetworkBillDetail);
        if (isAdd) {
            return R.ok("添加成功");
        } else {
            return R.fail("添加失败");
        }
    }

    @ApiOperation("修改")
    @PostMapping("/update")
    public R update(@RequestBody HqNetworkBillDetail hqNetworkBillDetail) {
        Boolean isUpdate = hqNetworkBillDetailService.update(hqNetworkBillDetail);
        if (isUpdate) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }

    @ApiOperation("修改落实承包区")
    @PostMapping("/updateSetContractArea")
    public R updateSetContractArea(@RequestBody HqNetworkBillDetail hqNetworkBillDetail) {
        Boolean isUpdate = hqNetworkBillDetailService.updateSetContractArea(hqNetworkBillDetail);
        if (isUpdate) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }

    @ApiOperation("修改落实客户")
    @PostMapping("/updateSetClient")
    public R updateSetClient(@RequestBody HqNetworkBillDetail hqNetworkBillDetail) {
        Boolean isUpdate = hqNetworkBillDetailService.updateSetClient(hqNetworkBillDetail);
        if (isUpdate) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }

    @ApiOperation("删除")
    @PostMapping("/delete")
    public R delete(Integer id) {
        Boolean isDelete = hqNetworkBillDetailService.deleteById(id);
        if (isDelete) {
            return R.ok("删除成功");
        } else {
            return R.fail("删除失败");
        }
    }

    @ApiOperation("搜索")
    @PostMapping("/search")
    public R search(@RequestBody HqNetworkBillDetailVo vo) {
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            System.out.println(startTime);
            System.out.println(endTime);
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }
        List<HqNetworkBillDetail> billDetailList = hqNetworkBillDetailService.search(vo);
        if (billDetailList == null || billDetailList.size() == 0) {
            return R.ok("暂无数据");
        } else {
            return R.ok(PageInfo.info(billDetailList));
        }
    }

    @ApiOperation("查询金额汇总")
    @PostMapping("/collectAmount")
    public R collectAmount(@RequestBody HqNetworkBillDetailVo vo) {
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            System.out.println(startTime);
            System.out.println(endTime);
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }
        return R.ok(hqNetworkBillDetailService.collectAmount(vo));
    }

    @ApiOperation("导出")
    @PostMapping("/export")
    public void export(@RequestBody HqNetworkBillDetailVo vo) {
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }
        String fileName = "attachment;filename=" + URLEncoder.createDefault().encode("网点账单明细", Charset.forName("utf-8")) + ".xls";
        response.setHeader("Content-Disposition", fileName);
        List<HqNetworkBillDetail> list = hqNetworkBillDetailService.search(vo);
        ExcelUtil<HqNetworkBillDetail> util = new ExcelUtil(HqNetworkBillDetail.class);
        util.exportExcel(response, list, "网点账单明细");
    }

    //    点击跳转
    @ApiOperation("点击跳转")
    @PostMapping("/point")
    public R point(@RequestBody HqNetworkBillPointVo vo) {
        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }
        List<HqNetworkBillDetail> list = hqNetworkBillDetailService.point(vo);
        List<TablePointVo> fieldList = tableService.getFieldAnnotationTwo(new HqNetworkBillDetail());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", PageInfo.info(list));
        jsonObject.put("fields", fieldList);
        if (list == null || list.size() == 0) {
            return R.fail("暂无数据");
        } else {
            return R.ok(jsonObject);
        }
    }

    @ApiOperation("异步导出明细excel")
    @PostMapping("/exportDetailAsync")
    public R exportDetailAsync(@RequestBody HqNetworkBillDetailVo vo) {
//        if (vo != null) {
//            String startTime = vo.getStartTime().replace("-", "");
//            String endTime = vo.getEndTime().replace("-", "");
//            vo.setStartTime(startTime);
//            vo.setEndTime(endTime);
//        }
//        hqNetworkBillDetailService.exportDetailAsync(vo);
//        return R.ok();

        if (vo == null) {
            return R.fail("参数不能为空");
        }

        if (vo != null) {
            String startTime = vo.getStartTime().replace("-", "");
            String endTime = vo.getEndTime().replace("-", "");
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }

        // 创建一个用于存储请求参数哈希键
        String requestKey = "EXPORT_DETAIL_REQUEST:" + vo.toString();
        // 创建一个用于存储请求时间戳的key
        String timestampKey = "EXPORT_DETAIL_TIMESTAMP:" + requestKey;

        // 检查是否有最近2分钟内的相同请求记录
        boolean existsInCache = stringRedisTemplate.opsForValue().setIfAbsent(timestampKey, LocalDateTime.now().toString(), 2, TimeUnit.MINUTES);
        if (!existsInCache) {
            // 已经存在2分钟内的相同请求记录，返回提示信息
            return R.fail("请勿重复下载，您在两分钟内已经发起过相同的导出请求！");
        }

        // 保存请求参数到Redis（可选，用于后续服务处理）
        stringRedisTemplate.opsForValue().set(requestKey, vo.toString(), 2, TimeUnit.MINUTES);

        // 调用服务进行异步导出
        hqNetworkBillDetailService.exportDetailAsync(vo);

        return R.ok("请前往总部下载中心查询进度");
    }
}
